import axios, { AxiosResponse, AxiosRequestConfig, AxiosError } from 'axios'
import { createElement } from 'react'
import ReactDOM from 'react-dom'
import { message, Spin } from 'antd'
import { history } from 'umi'
// 当前正在请求的数量
let requestCount: number = 0
const codeMessage = {
  400: '请求错误(400)',
  401: '未授权(401)',
  403: '拒绝访问(403)',
  404: '请求出错(404)',
  408: '请求超时(408)',
  500: '服务器错误(500)',
  501: '服务未实现(501)',
  502: '网络错误(502)',
  503: '服务不可用(503)',
  504: '网络超时(504)',
  505: 'HTTP版本不受支持(505)'
}

// 显示loading
function showLoading() {
  if (requestCount === 0) {
    if (!document.getElementById('loading')) {
      var dom = document.createElement('div')
      dom.setAttribute('id', 'loading')
      document.body.appendChild(dom)
      ReactDOM.render(
        createElement(Spin, {
          tip: '加载中...',
          size: 'large'
        }),
        dom
      )
    } else {
      document.getElementById('loading')!.style.display = 'flex'
    }
  }
  requestCount++
}

// 隐藏loading
function hideLoading() {
  requestCount--
  if (requestCount === 0) {
    document.getElementById('loading')!.style.display = 'none'
  }
}
const request = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (config.headers?.isLoading !== false) {
      showLoading()
    }
    return config
  },
  (error: AxiosError) => {
    if (error.config.headers?.isLoading !== false) {
      hideLoading()
    }
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    // 判断当前请求是否设置了不显示Loading
    if (response.config.headers?.isLoading !== false) {
      hideLoading()
    }
    if (response.data.code && response.data.code !== 200) {
      message.destroy()
      message.error(response.data.msg)
      // session已过期，请重新登录"
      if (response.data.code == 401) {
        history.replace('/')
        return {
          code: 401,
          obj: []
        }
      }
    }
    return response.data
  },
  (error: AxiosError) => {
    const { response, config } = error
    if (config.headers?.isLoading !== false) {
      hideLoading()
    }
    // 请求超时单独判断，请求超时没有 response
    if (error.message.indexOf('timeout') !== -1) {
      message.error('请求超时，请稍后再试')
    }
    // 对响应错误做点什么
    if (response) {
      message.error(codeMessage[response.status] ?? '请求出错')
    }

    return Promise.reject(error)
  }
)

export { request }
